package com.client.elements.canvas;

import com.google.gwt.canvas.client.Canvas;
import com.google.gwt.canvas.dom.client.Context2d;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.MouseMoveEvent;
import com.google.gwt.event.dom.client.MouseMoveHandler;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.Widget;

public class Tetris {
	static Canvas canvas_main;
	static Canvas back;

	static Context2d context_main;
	static Context2d backbuffer;

	final static Button btn = new Button("Start");

	public static Widget draw() {
		FlowPanel main = new FlowPanel();

		canvas_main = Canvas.createIfSupported();
		back = Canvas.createIfSupported();

		canvas_main.setCoordinateSpaceWidth(180);
		canvas_main.setCoordinateSpaceHeight(480);
		
		back.setCoordinateSpaceWidth(180);
		back.setCoordinateSpaceHeight(480);
		
		canvas_main.addStyleName("border");
		canvas_main.addStyleName("black_Background");
		

		context_main = canvas_main.getContext2d();
		backbuffer = back.getContext2d();

		timer(true);
		setHandlers();

		btn.addClickHandler(new ClickHandler() {

			@Override
			public void onClick(ClickEvent event) {
				if (btn.getText().equals("Start")) {
					timer(false);
					btn.setText("Stop");
				}else if (btn.getText().equals("Stop")) {
					timer(true);
					btn.setText("Start");
					context_main.clearRect(0, 0, 180, 480);
					backbuffer.clearRect(0, 0, 180, 480);
					x = 90;
					y = 0;
				}
			}
		});

		main.add(canvas_main);
		main.add(btn);

		return main;
	}
	
	static int x = 90, y = 0;

	final static Timer timer = new Timer() {
		@Override
		public void run() {
			context_main.clearRect(0, 0, 180, 480);
			context_main.drawImage(back.getCanvasElement(), 0, 0);
			for (int i = 0; i < 4; i++) {
				context_main.strokeRect(x - x % 30, y + i*30, 30, 30);
				if (y + 4*30 == 480) {
					backbuffer.strokeRect(x - x % 30, y + i*30, 30, 30);
					if (i == 3) {
						x = 90;
						y = 0;
					}
				}
			}
			
			context_main.setStrokeStyle("white");
			backbuffer.setStrokeStyle("white");


			y +=1;
		}
	};

	private static void timer(boolean stop) {
		if (stop == false) {
			timer.scheduleRepeating(25);		
		}else {
			timer.cancel();
		}
	}

	private static void setHandlers() {
		canvas_main.addMouseMoveHandler(new MouseMoveHandler() {
			
			@Override
			public void onMouseMove(MouseMoveEvent event) {
				x = event.getRelativeX(canvas_main.getElement());
			}
		});
	}
}